"""
Flask应用工厂
"""
from flask import Flask, jsonify
from flask_cors import CORS
import logging
import os
from config import get_config
from app.api import blueprints
from app.utils.exceptions import ERPMockException, ValidationError, AuthenticationError


def create_app(config_name: str = None) -> Flask:
    """创建Flask应用"""
    app = Flask(__name__,
                static_folder='../static')

    # 加载配置
    config = get_config(config_name)
    app.config.from_object(config)

    # 初始化CORS
    CORS(app)

    # 配置日志
    setup_logging(config)

    # 注册蓝图
    register_blueprints(app)

    # 注册错误处理器
    register_error_handlers(app)

    return app


def setup_logging(config):
    """设置日志配置"""
    # 创建logs目录
    log_dir = os.path.dirname(config.LOG_FILE)
    if log_dir and not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # 配置日志格式
    logging.basicConfig(
        level=getattr(logging, config.LOG_LEVEL),
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(config.LOG_FILE, encoding='utf-8'),
            logging.StreamHandler()
        ]
    )


def register_blueprints(app: Flask):
    """注册所有蓝图"""
    for blueprint in blueprints:
        app.register_blueprint(blueprint)


def register_error_handlers(app: Flask):
    """注册错误处理器"""

    @app.errorhandler(ValidationError)
    def handle_validation_error(e):
        """处理验证错误"""
        return jsonify({
            "code": e.code,
            "message": e.message
        }), 400

    @app.errorhandler(AuthenticationError)
    def handle_auth_error(e):
        """处理认证错误"""
        return jsonify({
            "code": e.code,
            "message": e.message
        }), 401

    @app.errorhandler(ERPMockException)
    def handle_erp_error(e):
        """处理ERP业务错误"""
        return jsonify({
            "code": e.code,
            "message": e.message
        }), 500

    @app.errorhandler(ValueError)
    def handle_value_error(e):
        """处理值错误"""
        return jsonify({
            "code": "400",
            "message": str(e)
        }), 400

    @app.errorhandler(Exception)
    def handle_generic_error(e):
        """处理通用错误"""
        logging.error(f"未处理的异常: {str(e)}", exc_info=True)
        return jsonify({
            "code": "500",
            "message": f"服务器内部错误: {str(e)}"
        }), 500